const http = require('http');
const fs = require('fs');
const parse = require('url').parse;

const hostname = '127.0.0.1';
const port = 3000;

const CODE_ERROR = 0;
const CODE_SUCCESS = 1;

var todoSet = new Set();

function send404(response) {
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.write('Error 404: resource not found.');
    response.end();
}

function sendMsg(response, msg) {
	response.writeHead(200, {'Content-Type': 'application/json;charset=UTF-8'});
    response.write(msg);
    response.end();
}

function readFile(response, filePath) {
	fs.readFile(filePath, (err, data) => {
		if (err) {
			return send404(response);
		}
		var html = data.toString();
		// html = html.replace('%', Array.from(todoSet).join('</li><li>'));
		response.writeHead(200, {'Content-Type': 'text/html'});
		response.end(html);
	});
}

function add(itemData) {
	todoSet.add(itemData);
}

function complete(itemData) {
	// 判断待办事项是否已添加
	if (!todoSet.has(itemData)) {
		return itemData + '-待办事项不存在';
	}
	if (todoSet.delete(itemData)) {
		return true;
	}
	return itemData + '-待办事项删除失败';
}

function findItemData(urlParse) {
	if (urlParse.query.length > 0) {
		var queryArray = urlParse.query.split('=');
		if (queryArray.length >= 2) {
			return decodeURI(queryArray[1]);
		}
	}
	return '';
}

function buildData(code, data, msg) {
	// 返回数据
	let retData = {
		'code':'',
		'data': [],
		'msg':''
	}
	retData.code = code;
	retData.data = data;
	retData.msg = msg;
	return retData;
}

const server = http.createServer((request, response) => {
	var urlParse = parse(request.url);
	var urlPath = urlParse.pathname;
	var itemData;
	if (urlPath == '/add' || urlPath == '/complete') {
		itemData = findItemData(urlParse);
		if (itemData.length == 0) {
			var data = buildData(CODE_ERROR, [], '输入数据有误');
			return sendMsg(response, JSON.stringify(data));
		}
	}
	switch (urlPath) {
		case '/':
			var filePath = 'public/index.html';
    		var absPath = './' + filePath;
			readFile(response, absPath);
			break;
		case '/query':
			var data = buildData(CODE_SUCCESS, Array.from(todoSet), '页面初始化');
			sendMsg(response, JSON.stringify(data));
			break;
		case '/add':
			add(itemData);
			var data = buildData(CODE_SUCCESS, Array.from(todoSet), '添加成功');
			sendMsg(response, JSON.stringify(data));
			break;
		case '/complete':
			var res = complete(itemData)
			if (res == true) {
				var data = buildData(CODE_SUCCESS, Array.from(todoSet), '待办已完成');
				return sendMsg(response, JSON.stringify(data)); 
			}
			var data = buildData(CODE_ERROR, [], res);
			sendMsg(response, JSON.stringify(data));
			break;
	}
});

server.listen(port, hostname, () => {
	console.log(`Server running at http://${hostname}:${port}/`)
})